﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace SF.Ucenter.tools
{
    /// <summary>
    /// user_ajax 的摘要说明
    /// </summary>
    public class user_ajax : IHttpHandler, IRequiresSessionState
    {
        Model.sf_user_info userInfo;
        string appWhere;
        BLL.bs_good_info goodInfoBll = new BLL.bs_good_info();
        BLL.bs_good_order orderInfoBll = new BLL.bs_good_order();
        BLL.bs_good_order_detail orderDetaBll = new BLL.bs_good_order_detail();

        BLL.sf_user_address addressBll = new BLL.sf_user_address();
        BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
        BLL.sf_user_info userBll = new BLL.sf_user_info();
        BLL.bs_good_cart shopCartBll = new BLL.bs_good_cart();
        public void ProcessRequest(HttpContext context)
        {
            /*验证用户是否登录*/
            if (context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info == null)
            {
                context.Response.Redirect("/mall/index.aspx");
            }
            userInfo = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
            appWhere = Utils.getWhereByInfo(userInfo.busnieseNum, userInfo.appNum, userInfo.templatesNum);
            string action = context.Request.QueryString["action"];

            switch (action)
            {
                case "get_moregoods": //获取更多商品 每次多加20条
                    get_moregoods(context);
                    break;
                case "add_card": //加入购物车
                    add_card(context);
                    break;
                case "delete_card": //删除购物车
                    delete_card(context);
                    break;
                case "cut_add_card": //购物车 增加减少数量
                    cut_add_card(context);
                    break;
                case "save_order": //保存订单
                    save_order(context);
                    break;
                case "cancel_order": //取消订单
                    order_cancel(context);
                    break;
                case "order_pay": //订单支付
                    order_pay(context);
                    break;
                //case "get_amount_sizecolor": //获取当前尺寸颜色的库存
                //    get_amount_sizecolor(context);
                //    break;
                case "delete_address": //删除地址
                    delete_address(context);
                    break;
                case "check_address": //默认地址
                    check_address(context);
                    break;
                case "add_address": //新增地址
                    add_address(context);
                    break;
            }
        }
        /// 增加地址
        private void add_address(HttpContext context)
        {
            string name = context.Request.QueryString["name"];
            string phone = context.Request.QueryString["phone"];
            string text = context.Request.QueryString["text"];
            Model.sf_user_address model = new Model.sf_user_address();
            model.addressNum = "DZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            model.userNum = userInfo.userNum;
            model.busnieseNum = userInfo.busnieseNum;
            model.appNum = userInfo.appNum;
            model.templatesNum = userInfo.templatesNum;
            model.phone = phone;
            model.personName = name;
            model.detailAddress = text;
            string res = new BLL.sf_user_address().Add(model) > 0 ? "0" : "-1";
            context.Response.Write(res);
        }
        /// 删除地址
        private void delete_address(HttpContext context)
        {
            long id = Convert.ToInt64(context.Request.QueryString["id"]);
            BLL.sf_user_address addressBll = new BLL.sf_user_address();
            string res = addressBll.Delete(id) ? "0" : "-1";
            context.Response.Write(res);
        }
        /// 默认地址
        private void check_address(HttpContext context)
        {
            string res = "";
            long id = Convert.ToInt64(context.Request.QueryString["id"]);
            string orderNum = context.Request.QueryString["orderNum"];
            BLL.sf_user_address addressBll = new BLL.sf_user_address();
            Model.sf_user_address address = addressBll.GetModel(id);
            address.isDefault = 1;
            res = addressBll.Update(address) ? "0" : "-1";
            if (!string.IsNullOrEmpty(orderNum))
            {
                BLL.sf_goods_order orderBll = new BLL.sf_goods_order();
                Model.sf_goods_order orderModel = orderBll.GetModel("orderNum='" + orderNum + "' and " + appWhere);
                orderModel.addressNum = address.addressNum;
                orderModel.addressText = address.personName + "," + address.phone + "," + address.detailAddress;
                res = orderBll.Update(orderModel) ? "0" : "-2";
            }
            context.Response.Write(res);
        }

        /// 删除购物车
        private void delete_card(HttpContext context)
        {
            long id = Convert.ToInt64(context.Request.QueryString["id"]);
            BLL.bs_good_cart cartBll = new BLL.bs_good_cart();
            string res = cartBll.Delete(id) ? "" : "-1";
            context.Response.Write(res);
        }
        /// 购物车 增加减少数量
        private void cut_add_card(HttpContext context)
        {
            long id = Convert.ToInt64(context.Request.QueryString["id"]);
            int num = Convert.ToInt32(context.Request.QueryString["num"]);
            BLL.bs_good_cart cartBll = new BLL.bs_good_cart();
            Model.bs_good_cart model = cartBll.GetModel(id);
            model.number = num;
            model.totalPrice = model.price * num;
            string res = cartBll.Update(model) ? "" : "-1";
            context.Response.Write(res);
        }

        /// <summary>
        /// 获取当前尺寸颜色的库存
        /// </summary>
        /// <param name="context"></param>
        //private void get_amount_sizecolor(HttpContext context)
        //{
        //    BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
        //    string goodid = context.Request.QueryString["goodid"];
        //    string sizeid = context.Request.QueryString["sizeid"];
        //    string colorid = context.Request.QueryString["colorid"];
        //    Model.sf_goods_info good = goodInfoBll.GetModel(Convert.ToInt64(goodid));
        //    string dan = good.goodsTypeNum == "clothes" ? "件" : good.goodsTypeNum == "trousers" ? "条" : good.goodsTypeNum == "shoes" ? "双" : "";
        //    Model.sf_goods_amounts amount = amountBll.GetModel(" goodsNum='" + good.goodsNum + "' and sizeId=" + sizeid + " and colorId=" + colorid + " and " + appWhere);
        //    string res = amount != null ? amount.amount + "_" + dan : "";
        //    context.Response.Write(res);
        //}


        /// <summary>
        /// 订单 支付
        /// </summary>
        /// <param name="context"></param>
        private void order_pay(HttpContext context)
        {
            //获取传入订单orderId参数
            string orderId = context.Request.QueryString["orderId"];
            //获取 订单 对象
            Model.bs_good_order orderInfo = orderInfoBll.GetModel("orderId='" + orderId + "' and " + appWhere);
            orderInfo.payTime = DateTime.Now;
            orderInfo.payStatus = SF.Common.DTEnums.PayStatusEnum.DonePay.ToString();
            context.Response.Write(orderInfoBll.Update(orderInfo));

        }


        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        /// <param name="context"></param>
        private void add_card(HttpContext context)
        {
            //    return;
            //获取传入商品id，num参数
            string id = context.Request.QueryString["id"];
            string num = context.Request.QueryString["num"];
            //string sizeId = context.Request.QueryString["sizeId"];
            //string colorId = context.Request.QueryString["colorId"];
            //创建 cart对象
            Model.bs_good_cart cart = new Model.bs_good_cart();
            cart.lastTime = DateTime.Now;
            //根据id 获取商品对象
            Model.bs_good_info good = goodInfoBll.GetModel(Convert.ToInt32(id));
            //Model.sf_goods_amounts amount = amountBll.GetModel("goodsNum='" + good.goodsNum + "' and sizeId=" + sizeId + " and colorId=" + colorId + " and " + appWhere);
            if (good.stock <= 0)
            {
                context.Response.Write("-2");
                return;
            }
            //判断是否存在该商品在购物车中
            if (shopCartBll.Exists("goodId='" + good.id + "' and userId='" + userInfo.id + "' and " + appWhere))
            {
                //if (shopCartBll.Exists("goodsNum='" + good.goodsNum + "' and userNum='" + userInfo.userNum + "' and amountId=" + amount.id + " and " + appWhere))
                //{
                context.Response.Write("-1");
                //}
            }
            else
            {
                //对 cart对象赋值
                cart.busnieseNum = userInfo.busnieseNum;
                cart.appNum = userInfo.appNum;
                cart.templatesNum = userInfo.templatesNum;
                cart.userId = userInfo.id;
                cart.goodId = good.id;
                cart.price = good.sellPrice;
                cart.number = Convert.ToInt32(num);
                cart.totalPrice = cart.price * cart.number;
                //cart.amountId = amount != null ? Convert.ToInt32(amount.id) : 0;

                //Labix Mark：这个方法总是返回-2，导致前台一直报--请再次选择商品属性
                context.Response.Write(shopCartBll.Add(cart));
            }
        }

        /// <summary>
        /// 保存用户订单
        /// </summary>
        private void save_order(HttpContext context)
        {
            try
            {
                //获取传入商品id，num参数
                string id = context.Request.QueryString["id"];  //Labix：商品Id集合，例如：1,2,3
                string num = context.Request.QueryString["num"];  //Labix：商品数量集合，例如：6,6,8
                //string sizeId = context.Request.QueryString["sizeId"];
                //string colorId = context.Request.QueryString["colorId"];
                //判断是否为 购物车 支付
                string type = context.Request.QueryString["type"];
                List<Model.bs_good_cart> cartList = new List<Model.bs_good_cart>();
                if (!string.IsNullOrEmpty(type) && type.Equals("cart"))
                {
                    string[] temp = id.Split(',');
                    id = "";
                    for (int i = 0; i < temp.Length; i++)
                    {
                        Model.bs_good_cart cart = shopCartBll.GetModel(Convert.ToInt32(temp[i]));
                        id += goodInfoBll.GetModel("id='" + cart.goodId + "' and " + appWhere).id + ",";
                        cartList.Add(cart);
                        shopCartBll.Delete(Convert.ToInt32(temp[i]));  //Labix：从购物车删除
                    }
                    id = id.Substring(0, id.Length - 1);
                }

                //创建 订单模型，产生 随机订单编号
                Model.bs_good_order orderInfo = new Model.bs_good_order("orderId");  //Laibx：传这个参数，可产生随机订单编号
                orderInfo.userNum = userInfo.userNum;
                orderInfo.busnieseNum = userInfo.busnieseNum;
                orderInfo.appNum = userInfo.appNum;
                orderInfo.templatesNum = userInfo.templatesNum;

                orderInfo.payStatus = SF.Common.DTEnums.PayStatusEnum.ToPay.ToString();  //Labix：支付状态设置为待支付
                orderInfo.status = SF.Common.DTEnums.OrderStatusEnum.Normal.ToString();  //Labix：订单状态设置为正常
                orderInfo.payWay = SF.Common.DTEnums.PayWayEnum.WxPay.ToString();  //Labix：支付方式默认为微信支付

                orderInfo.totalPrice = 0;  //Labix：总价先设置为0
                     
                //拆分商品id及num
                string[] ids = id.Split(',');
                string[] nums = num.Split(',');
                //string[] sizeIds = sizeId != null ? sizeId.Split(',') : null;
                //string[] colorIds = colorId != null ? colorId.Split(',') : null;
                //获取商品模型集合 及 订单小计
                List<Model.bs_good_info> lists = new List<Model.bs_good_info>();
                for (int i = 0; i < ids.Length; i++)
                {
                    Model.bs_good_info good = goodInfoBll.GetModel(Convert.ToInt32(ids[i]));
                    orderInfo.totalPrice += good.sellPrice * Convert.ToInt32(nums[i]);
                    //根据 商品id、sizeid、colorid获取库存id
                    //if (good.typeNum.Equals("maquillage"))
                    //{
                    //    good.num = 0;
                    //}
                    //else
                    //{
                    //    good.num = Convert.ToInt32(amountBll.GetModel("goodsNum='" + good.goodsNum + "' and sizeId=" + sizeIds[i] + " and colorId=" + colorIds[i] + " and " + appWhere).id);
                    //}
                    lists.Add(good);
                }
                //根据登入用户，获取其 默认收货地址
                Model.sf_user_address address = addressBll.GetModel("userNum='" + orderInfo.userNum + "' and isDefault>=1 and " + appWhere);
                //orderInfo.addressNum = address != null ? address.addressNum : "";
                orderInfo.receiveInfo = address != null ? address.personName + "|" + address.phone + "|" + address.detailAddress : "";
                orderInfo.expressStatus = SF.Common.DTEnums.ExpressStatusEnum.ToSend.ToString();
                orderInfo.expressName = "";
                orderInfo.expressNum = "";

                //模拟事务，错误将删除错误数据
                int error = 0;
                long addOrder = orderInfoBll.Add(orderInfo);
                for (int i = 0; i < lists.Count && addOrder > 0; i++)
                {
                    Model.bs_good_order_detail detal = new Model.bs_good_order_detail();
                    detal.busnieseNum = userInfo.busnieseNum;
                    detal.appNum = userInfo.appNum;
                    detal.templatesNum = userInfo.templatesNum;
                    detal.orderId = addOrder;  //Labix：订单Id
                    detal.goodId = lists[i].id;
                    detal.number = Convert.ToInt32(nums[i]);
                    detal.price = lists[i].sellPrice;
                    detal.totalPrice = detal.number * detal.price;
                    //detal.amountId = lists[i].num;
                    if (orderDetaBll.Add(detal) < 1)
                    {
                        error++;
                        break;
                    }
                }
                if (error > 0)
                {
                    orderInfoBll.Delete(orderInfo.id);
                    orderDetaBll.DeleteListByOrderId(orderInfo.id, appWhere);
                    for (int i = 0; i < cartList.Count; i++)
                    {
                        shopCartBll.Add(cartList[i]);
                    }
                }
                //检测是否成功保存
                //成功-订单编号
                if (orderInfoBll.Exists("orderNum='" + orderInfo.orderNum + "' and " + appWhere))
                {
                    context.Response.Write(addOrder);
                }
                else
                {
                    context.Response.Write("");
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 取消用户订单
        /// </summary>
        /// <param name="context"></param>
        private void order_cancel(HttpContext context)
        {
            //获取传入订单id
            long orderId = Convert.ToInt64(context.Request.QueryString["orderId"]);
            bool isOk = orderInfoBll.Delete("id='" + orderId + "'");
            if (isOk)
            {
                orderDetaBll.DeleteListByOrderId(orderId, appWhere);
                context.Response.Write(isOk);
            }
            else
            {
                context.Response.Write("false");
            }
        }

        /// <summary>
        /// 获取更多商品 每次多加20条
        /// </summary>
        /// <param name="context"></param>
        private void get_moregoods(HttpContext context)
        {
            string appWhere = Utils.getWhereByInfo(userInfo.busnieseNum, userInfo.appNum, userInfo.templatesNum);
            System.Collections.IDictionary dict = System.Configuration.ConfigurationManager.GetSection("requestStr") as System.Collections.IDictionary;
            int pageNum = Convert.ToInt32(dict["goodsNum"].ToString());
            string res = "";
            int moreNum = Convert.ToInt32(context.Request.QueryString["moreNum"]);
            int hiddenNum = Convert.ToInt32(context.Request.QueryString["hiddenNum"]);
            BLL.sf_goods_info goodInfoBll = new BLL.sf_goods_info();
            BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
            DataTable dt = goodInfoBll.GetList(appWhere + " and status=1 order by sort").Tables[0];
            if (dt.Rows.Count > (moreNum * pageNum + hiddenNum))
            {
                for (int i = (moreNum * pageNum + hiddenNum); i < dt.Rows.Count && i < ((moreNum + 1) * pageNum + hiddenNum); i++)
                {
                    if (amountBll.Exists(appWhere + " and goodsNum='" + dt.Rows[i]["goodsNum"] + "'") || (!string.IsNullOrEmpty(dt.Rows[i]["num"].ToString()) && Convert.ToInt32(dt.Rows[i]["num"]) > 0))
                    {
                        res += dt.Rows[i]["id"] + "_" + dt.Rows[i]["showImgs"] + "_" + dt.Rows[i]["names"] + "_" + dt.Rows[i]["goodsTypeNum"] + "_" + dt.Rows[i]["salesPrice"] + "_" + dt.Rows[i]["showPrice"] + ",";
                    }
                    else
                    {
                        hiddenNum++;
                    }
                }
            }
            res += res == "" ? "" : "^" + hiddenNum;
            context.Response.Write(res);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}